package cn.etgps.etgps.frgament;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.etgps.etgps.R;
import cn.etgps.etgps.adapter.GarageListAdapter;
import cn.etgps.etgps.base.BaseActivity;
import cn.etgps.etgps.blmanager.TruckManager;
import cn.etgps.etgps.dataEntity.Model;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.ui.MapMarkerActivity;
import cn.etgps.etgps.ui.MeActivity;
import cn.etgps.etgps.utils.Constant;
import cn.etgps.etgps.utils.MainUsedInterface;
import cn.etgps.etgps.view.AutoListView;
import cn.etgps.etgps.view.CategorySelectView;
import cn.etgps.etgps.view.ExpandButton;
import cn.etgps.etgps.view.SearchView;
import cn.etgps.etgps.view.TitleBar;

/**
 * GarageFragment for the first tab content
 *
 * @author Nicky
 */
public class GarageFragment extends BaseFragment implements AdapterView.OnItemClickListener,
        MainUsedInterface.MainButtonClickListener, View.OnClickListener, AutoListView.OnRefreshListener,
        AutoListView.OnLoadListener, SearchView.SearchListener {
    /**
     * Note the list view status
     */
    private static int mListViewStatus = -1;
    /**
     * Note the showing data page count
     */
    private static int mListPageCount = 1;
    /**
     * Handler to notify activity some message
     */
    private Handler mParentHandler = null;
    private TitleBar mTitlebarView = null;
    private AutoListView mListView = null;
    private GarageListAdapter mAdapter = null;
    private TextView mSearchNoResult = null;
    /**
     * 现在的卡车数据
     */
    private List<Model> mTruckBeans = new ArrayList<Model>();
    /**
     * 搜索时候显示的卡车数据
     */
    private List<Model> mSearchedTruckBeans = new ArrayList<Model>();
    /**
     * 卡车的管理类
     */
    private TruckManager mTruckManager = null;
    /**
     * 获取卡车数据的线程
     */
    private GetGarageInfoTask mLoadTruckStatusTask = null;
    /**
     * 搜索功能线程
     */
    private DoSearchTask mSearchTask = null;
    /**
     * 次版本屏蔽的排序功能
     */
    private ExpandButton mSortByType = null;
    private ExpandButton mSortByStatus = null;
    private ExpandButton mSortByTasks = null;
    /**
     * 用来传递点击事前的自定义监听函数
     */
    private MainUsedInterface.MainButtonClickListener mMainButtonListener = null;
    /**
     * 次版本屏蔽的排序功能
     */
    private PopupWindow mCateoryChooseWindow = null;
    private String mCurrentTypeSortType = "";
    private String mCurrentStatusSortType = "";
    private String mCurrentTaskSortType = "";
    private int mShowingCategoryIndex = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.garage_fragment_view, null);
        mSearchNoResult = (TextView) view.findViewById(R.id.no_result_notify);
        mTitlebarView = (TitleBar) view.findViewById(R.id.title_bar);
        mTitlebarView.initTitleBarInfo("", "", R.drawable.title_icon_map, "", R.drawable.title_icon_person, true);
        mTitlebarView.setMainClickListener(mMainButtonListener, getString(R.string.title_btn_map_mode),
                getString(R.string.title_btn_me));
        mListView = (AutoListView) view.findViewById(R.id.list);
        mListView.setOnRefreshListener(this);
        mListView.setOnLoadListener(this);
        mListView.setOnItemClickListener(this);
        mAdapter = new GarageListAdapter(this.getActivity(), mListView, mTruckBeans);
        mListView.setAdapter(mAdapter);
        mTruckManager = new TruckManager(getActivity());
        mTitlebarView.getSearchView().initSearchView(this, false);
        mCurrentTypeSortType = this.getResources().getStringArray(R.array.truck_type_category)[0];
        mCurrentStatusSortType = this.getResources().getStringArray(R.array.truck_driving_status_category)[0];
        mCurrentTaskSortType = this.getResources().getStringArray(R.array.truck_task_status_category)[0];
        mSortByType = (ExpandButton) view.findViewById(R.id.truck_category);
        mSortByType.setOnClickListener(this);
        mSortByType.setButtonName(mCurrentTypeSortType);
        mSortByStatus = (ExpandButton) view.findViewById(R.id.status_category);
        mSortByStatus.setOnClickListener(this);
        mSortByStatus.setButtonName(mCurrentStatusSortType);
        mSortByTasks = (ExpandButton) view.findViewById(R.id.task_category);
        mSortByTasks.setOnClickListener(this);
        mSortByTasks.setButtonName(mCurrentTaskSortType);
        loadData(AutoListView.REFRESH);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position > mAdapter.getCount()) {
            return;
        }
        mAdapter.showCategoryChooseWindow(position - mListView.getHeaderViewsCount());
    }

    /**
     * Handler which used to notify parent some message
     */
    public void setParentHandler(Handler parentHandler, MainUsedInterface.MainButtonClickListener listener) {
        mParentHandler = parentHandler;
        mMainButtonListener = listener;
    }

    /**
     * Load data
     */
    private void loadData(final int what) {
        mListViewStatus = what;
        if (mTruckManager.checkNetwork(getActivity())) {
            if (!mTitlebarView.getSearchView().getInput().equals("")) {
                if (mSearchTask != null && mSearchTask.getStatus() == AsyncTask.Status.RUNNING) {
                    mSearchTask.cancel(true);
                    mSearchTask = null;
                }
                mSearchTask = new DoSearchTask();
                mSearchTask.execute(mTitlebarView.getSearchView().getInput());
            } else {
                if (mLoadTruckStatusTask != null && mLoadTruckStatusTask.getStatus() == AsyncTask.Status.RUNNING) {
                    mLoadTruckStatusTask.cancel(true);
                    mTruckManager.closeDBManager();
                }
                mLoadTruckStatusTask = new GetGarageInfoTask();
                mLoadTruckStatusTask.execute();
            }
        } else {
            mTruckManager.showToastMessage(getString(R.string.toast_no_network), 1000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLoadTruckStatusTask != null && mLoadTruckStatusTask.getStatus() == AsyncTask.Status.RUNNING) {
            mLoadTruckStatusTask.cancel(true);
            mTruckManager.closeDBManager();
        }
    }

    @Override
    public void onClick(View v) {
        mShowingCategoryIndex = v.getId();
        switch (mShowingCategoryIndex) {
            case R.id.truck_category:
                showCategoryChooseWindow(R.array.truck_type_category);
                break;
            case R.id.status_category:
                showCategoryChooseWindow(R.array.truck_driving_status_category);
                break;
            case R.id.task_category:
                showCategoryChooseWindow(R.array.truck_task_status_category);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        loadData(AutoListView.REFRESH);
    }

    @Override
    public void onLoad() {
        loadData(AutoListView.LOADMORE);
    }

    @Override
    public void doSearch(String key) {
        mListPageCount = 1;
        resetSorts();
        if (key.equals("")) {
            mListView.setResultSize(0);
            mSearchedTruckBeans.clear();
            mAdapter.resetData(mTruckBeans);
            mSearchNoResult.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        } else {
            loadData(AutoListView.REFRESH);
        }
    }


    private void resetSorts() {
        mCurrentTypeSortType = this.getResources().getStringArray(R.array.truck_type_category)[0];
        mCurrentStatusSortType = this.getResources().getStringArray(R.array.truck_driving_status_category)[0];
        mCurrentTaskSortType = this.getResources().getStringArray(R.array.truck_task_status_category)[0];
        mSortByType.setButtonName(mCurrentTypeSortType);
        mSortByStatus.setButtonName(mCurrentStatusSortType);
        mSortByTasks.setButtonName(mCurrentTaskSortType);
        mShowingCategoryIndex = -1;
    }

    /**
     * Show category menu
     */
    public void showCategoryChooseWindow(int arrayId) {
        LayoutInflater layoutInflater = this.getActivity().getLayoutInflater();
        CategorySelectView view = new CategorySelectView(getActivity());
        String defaultName = "";
        switch (arrayId) {
            case R.array.truck_type_category:
                mSortByType.expandButton(true);
                defaultName = mCurrentTypeSortType;
                break;
            case R.array.truck_driving_status_category:
                mSortByStatus.expandButton(true);
                defaultName = mCurrentStatusSortType;
                break;
            case R.array.truck_task_status_category:
                mSortByTasks.expandButton(true);
                defaultName = mCurrentTaskSortType;
                break;
            default:
                break;
        }
        view.initCategoryList(this.getResources().getStringArray(arrayId), defaultName, this);
        mCateoryChooseWindow = new PopupWindow(view, AbsListView.LayoutParams.WRAP_CONTENT,
                AbsListView.LayoutParams.MATCH_PARENT, true);
        mCateoryChooseWindow.setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        mCateoryChooseWindow.setBackgroundDrawable(dw);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideCategoryChooseWindow();
                return false;
            }
        });
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    hideCategoryChooseWindow();
                }
                return false;
            }
        });
        hideCategoryChooseWindow();
        mCateoryChooseWindow.showAsDropDown(mSortByStatus, 0, 1);
    }

    /**
     * Hide category menu
     */
    public void hideCategoryChooseWindow() {
        if (null != mCateoryChooseWindow && mCateoryChooseWindow.isShowing()) {
            mCateoryChooseWindow.dismiss();
            mSortByType.expandButton(false);
            mSortByType.setButtonName(mCurrentTypeSortType);
            mSortByStatus.expandButton(false);
            mSortByStatus.setButtonName(mCurrentStatusSortType);
            mSortByTasks.expandButton(false);
            mSortByTasks.setButtonName(mCurrentTaskSortType);
            mCateoryChooseWindow = null;
            mShowingCategoryIndex = -1;
        }
    }

    @Override
    public void clickListListener(String listName, int index, Model model) {

    }

    @Override
    public void clickButtonListener(String name) {
        if (name.equals(getString(R.string.title_btn_map_mode))) {
            Intent intent = new Intent(getActivity(), MapMarkerActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getActivity(), MeActivity.class);
            startActivity(intent);
        }
        switch (mShowingCategoryIndex) {
            case R.id.truck_category:
                mCurrentTypeSortType = name;
                break;
            case R.id.status_category:
                mCurrentStatusSortType = name;
                break;
            case R.id.task_category:
                mCurrentTaskSortType = name;
                break;
            default:
                break;
        }
        hideCategoryChooseWindow();
        loadData(AutoListView.REFRESH);
    }

    @Override
    public void getInputStringListener(String btnName, String[] inputs) {

    }


    /**
     * Thread to load user icon
     *
     * @author Nicky
     */
    class GetGarageInfoTask extends AsyncTask<String, Integer, String> {
        String result = "";
        List<Model> stautsList = new ArrayList<Model>();

        @Override
        protected String doInBackground(String... params) {
            ((BaseActivity) getActivity()).showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            //如果是下拉刷新就要
            if (mListViewStatus == AutoListView.LOADMORE && mTruckBeans != null && mTruckBeans.size() > 0) {
                mListPageCount++;
            } else {
                mListPageCount = 1;
            }
            result = mTruckManager.getTrucksFromServer(stautsList, mListPageCount);
            if (mListPageCount == 1) {
                mTruckManager.saveTrucksToLocalDB(stautsList);
                mTruckManager.closeDBManager();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("")) {
                if (mListViewStatus == AutoListView.LOADMORE) {
                    mListView.onLoadComplete();
                    if (stautsList != null && stautsList.size() > 0) {
                        mTruckBeans.addAll(stautsList);
                    }
                } else {
                    if (stautsList != null && stautsList.size() > 0) {
                        mTruckBeans.clear();
                        mTruckBeans.addAll(stautsList);
                        mSearchNoResult.setVisibility(View.GONE);
                        mListView.setVisibility(View.VISIBLE);
                    } else {
                        mSearchNoResult.setVisibility(View.VISIBLE);
                        mListView.setVisibility(View.GONE);
                    }
                }
                mListView.setResultSize(stautsList.size());
                if (stautsList != null && stautsList.size() > 0) {
                    stautsList.clear();
                    mAdapter.notifyDataSetChanged();
                }
            } else if (Constant.CONNECT_TO_SERVER_FAILED.equals(result)) {
                mTruckManager.showToastMessage(getString(R.string.toast_connect_server_failed), 2000);
            } else {
                mTruckManager.showToastMessage(result, 2000);
            }
            mListViewStatus = -1;
            mListView.onRefreshComplete();
            mListView.onLoadComplete();
            ((BaseActivity) getActivity()).dismissNormalDialog();
        }
    }

    /**
     * Thread to load user icon
     *
     * @author Nicky
     */
    class DoSearchTask extends AsyncTask<String, Integer, String> {
        String result = "";
        List<Model> stautsList = new ArrayList<Model>();

        @Override
        protected String doInBackground(String... params) {
            ((BaseActivity) getActivity()).showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            if (mListViewStatus == AutoListView.LOADMORE) {
                mListPageCount++;
            } else {
                mListPageCount = 1;
            }
            result = mTruckManager.searchTruckFromServer(stautsList, params[0], mListPageCount);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (mListViewStatus == AutoListView.LOADMORE) {
                mListView.onLoadComplete();
                if (stautsList != null && stautsList.size() > 0) {
                    mSearchedTruckBeans.addAll(stautsList);
                    mAdapter.notifyDataSetChanged();
                }
            } else {
                if (stautsList != null && stautsList.size() > 0) {
                    mSearchedTruckBeans.clear();
                    mSearchedTruckBeans.addAll(stautsList);
                    mSearchNoResult.setVisibility(View.GONE);
                    mListView.setVisibility(View.VISIBLE);
                } else {
                    mSearchNoResult.setVisibility(View.VISIBLE);
                    mListView.setVisibility(View.GONE);
                }
                mAdapter.resetData(mSearchedTruckBeans);
            }
            mListView.setResultSize(stautsList.size());
            if (stautsList != null && stautsList.size() > 0) {
                stautsList.clear();
            }
            mListViewStatus = -1;
            mListView.onRefreshComplete();
            mListView.onLoadComplete();
            ((BaseActivity) getActivity()).dismissNormalDialog();
        }
    }
}
